package com.it1997.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration // 该注解声明该类是一个配置类,不能省略
@PropertySource({"file:config/db.properties","classpath:mybatis.properties"})
public class JdbcConfig {
    // 驱动名称
    @Value("${database.driver}")
    private String driverClassName;
    // 数据库连接地址
    @Value("${database.url}")
    private String url;
    // 数据库用户名
    @Value("${database.username}")
    private String username;
    // 数据库密码
    @Value("${database.password}")
    private String password;
    @Value("${mybatis.aliasesPackage}")
    public String aliasesPackage;
    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;

    // 配置数据源
    @Bean("dataSource")
    public DataSource createDataSource() {
        // 创建Druid连接池对象
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDefaultAutoCommit(true); // 自动提交事务，默认true
        return dataSource;
    }

    // 配置创建数据库连接的对象
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        // 设置连接池
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 实体类起别名
        sqlSessionFactoryBean.setTypeAliasesPackage(aliasesPackage);
        // 配置mapper.xml配置文件路径
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        return sqlSessionFactoryBean;
    }

}

